#include "mainwindow.h"
#include "ui_mainwindow.h"

#pragma execution_character_set("utf-8")

#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>
#include <QTime>
#include <QDir>
#include <QFile>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    globalMark=0;
}

MainWindow::~MainWindow()
{
    delete ui;
}

//打开图片
void MainWindow::on_action_open_triggered()
{
     ui->show_label->clear();//先清除展示图片的框
     //打开图片
     QString fileName = QFileDialog::getOpenFileName(
                 this, tr("open image file"),
                 "./", tr("Image files(*.bmp *.jpg *.pbm *.pgm *.png *.ppm *.xbm *.xpm);;All files (*.*)"));

     if(fileName.isEmpty())
     {
         QMessageBox mesg;
         mesg.warning(this,"提示信息","打开图片失败!");
         return;
     }
     else
     {
         QImage img(fileName);
         img=img.scaled(ui->show_label->width(),ui->show_label->height(),Qt::KeepAspectRatio);//Qt::KeepAspectRatio使图片能够适应大小，不让框变形
         ui->show_label->setPixmap(QPixmap::fromImage(img));
         if(img.isNull())
         {
             QMessageBox::information(this,"提示信息","打开图片失败");
         }
         else
         {
             globalMark=1; //存储标记，用于判断是否有图片
             globalImg=img;
         }
     }

}

//保存图片
void MainWindow::on_action_save_triggered()
{
    if( globalMark==1)//如果标记为1，证明有图片正在被编辑，不然没有则不需要保存
    {
        QString filePath;//存储保存路径
        QString saveName="保存实验图";//保存图片名字
        QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
        QString str = time.toString("yyyyMMdd_hhmmss"); //设置显示格式
        saveName += str;
        filePath = QFileDialog::getExistingDirectory(this,"");//获取文件夹路径
        if(filePath.isEmpty())
        {
            QMessageBox::information(this,"提示信息","保存失败");
        }
        else
        {
            QImage images;
            images=globalImg;//获取修改的图片

            //将图片重新命名并保存至文件夹里
            QString savePath=QString("%1//%2.png").arg(filePath).arg(saveName);
            images.save(savePath);//QImage保存方法
            QMessageBox::information(this,"提示信息","保存成功");
        }
    }
    else
    {
        QMessageBox::information(this,"提示信息","保存失败，图片未做更改");
    }
}


void MainWindow::on_action_back_triggered()
{

}
